﻿#region Using directives
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Core.Message.Entities;
using Core.Controls.Message;
using Core.ExceptionHandling;
using Core.Common.Session;
using vHCS.TS.Business;
using Telerik.Web.UI;

#endregion

namespace vHCS.K2App.MdlK2.OT.Ver1
{
    public partial class TS_ApproveOT : Core.NTier.UserInterface.BaseFormNotPer
    {
        #region const
        protected const string _EmpID = "EmpID";
        protected const string _MonthYear = "MonthYear";
        protected const string _OverTimeID = "OverTimeID";
        #endregion

        #region Protected Methods
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                }
                string strEmpID = "";
                string strMonthYear = "";
                string strOverTimeID = "";
                try
                {
                    string sharedUser = Request.QueryString["SharedUser"] != null ? Request.QueryString["SharedUser"].ToString() : string.Empty;
                    strEmpID = K2CoreLib.K2Utils.GetDataField(Request.QueryString["sn"].ToString(), "EmpID", sharedUser);
                    strMonthYear = K2CoreLib.K2Utils.GetDataField(Request.QueryString["sn"].ToString(), "MonthYear", sharedUser);
                    strOverTimeID = K2CoreLib.K2Utils.GetDataField(Request.QueryString["sn"].ToString(), "OverTimeID", sharedUser);
                }
                catch (Exception ex)
                {
                    btnSaveBot.Enabled = false;
                    btnSaveTop.Enabled = false;
                    //BusinessLogicCustomException ex = new BusinessLogicCustomException("12634");
                    throw ex;
                }

                this.txtEmpID.Text = strEmpID;
                this.txtMonthYear.Text = strMonthYear;
                txtOverTimeID.Text = strOverTimeID;
                long EmpID = this.txtEmpID.Text != "" ? Convert.ToInt64(this.txtEmpID.Text) : 0;
                this.ucSerach.LoadEmpInfoByEmpId(EmpID);
                txtEmpID.Text = this.ucSerach.EmployeeId.ToString();
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
        /// <summary>
        /// Write dữ liệu cho lưới danh sách 
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// [Author: HongTT7] [Create Date: 13/05/2011]
        /// </summary>
        protected void dtg_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            try
            {
                if (e.Item is GridDataItem)
                {
                    GridDataItem item = (GridDataItem)e.Item;

                    CheckBox chkNghiBu = (CheckBox)item.FindControl("chkNghiBu");
                    chkNghiBu.Checked = Convert.ToBoolean(item["IsCompensation"].Text.ToString());
                }
            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }
        }   /// <summary>
        /// Xử lý button Save-- trạng thái chưa gửi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// [Author: HongTT7] [Create Date: 13/05/2011]
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.UpdateOverTime();
                
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
        #endregion

        #region Private Methods
        /// <summary>        
        /// Update quản lý ngoài giờ của nhân viên
        /// [Author: HongTT7] [Create Date: 13/06/2011]
        /// </summary>    
        public void UpdateOverTime()
        {
            try
            {
                List<TS_OverTimeBL> lstInfo = new List<TS_OverTimeBL>();

                for (int i = 0; i < dtg.Items.Count; i++)
                {
                    GridDataItem item = (GridDataItem)dtg.Items[i];

                    TS_OverTimeBL bl = new TS_OverTimeBL();
                    long OverTimeID = item["OverTimeID"].Text.Trim() != "&nbsp;" ? Convert.ToInt32(item["OverTimeID"].Text.Trim()) : 0;
                    RadTextBox txtOTHoursNightApprove = (RadTextBox)item.FindControl("txtOTHoursNightApprove");
                    //RadTextBox txtOTHoursDayApprove = (RadTextBox)item.FindControl("txtOTHoursDayApprove");
                    RadNumericTextBox txtOTHoursDayApprove = (RadNumericTextBox)item.FindControl("txtOTHoursDayApprove");
                    CheckBox chkNghiBu = (CheckBox)item.FindControl("chkNghiBu");

                    bl.OverTimeID = OverTimeID;
                    bl.OTHoursNightApprove = txtOTHoursNightApprove.Text.Trim() != "" ? TS_clsCommon.ConvertFromStringToFloat(txtOTHoursNightApprove.Text.Trim()) : 0.00;
                    //bl.OTHoursDayApprove = txtOTHoursDayApprove.Text.Trim() != "" ? TS_clsCommon.ConvertFromStringToFloat(txtOTHoursDayApprove.Text.Trim()) : 0.00;
                    bl.OTHoursDayApprove = Convert.ToDouble(txtOTHoursDayApprove.Value);
                    bl.IsCompensation = chkNghiBu.Checked;
                    bl.CreatedUser = SessionManager.UserDomain;
                    bl.StatusID = cboStatus.SelectedValue.Equals("Reject") ? 8 : 4;
                    lstInfo.Add(bl);
                }
                if (lstInfo.Count > 0)
                {
                    TS_OverTimeCollection col = new TS_OverTimeCollection();
                    int nodeID = col.UpdateOverTimeTable_K2(lstInfo);
                    if (nodeID == 1)
                    {
                        //thông báo cập nhật thành công
                        this.VacationList.CacheClear();
                        this.dtg.Rebind();
                        ClientScript.RegisterStartupScript(Page.GetType(), "", string.Format("SaveCallback({0});", string.Empty), true);
                        SubmitK2();
                        MessageBox.ShowByMessCode("10010", MessageType.Successful);
                    }
                }
                ClientScript.RegisterStartupScript(Page.GetType(), "ClosePage", "ClosePage();", true);
            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }
        }

        /// <summary>
        /// Xử lý phê duyệt trên K2
        /// </summary>
        private void SubmitK2()
        {
            try
            {
                //int processInstance = K2CoreLib.K2Utils.GetWorklistItem(Request.QueryString["sn"].ToString()).ProcessInstance.ID;
                //string OverTimeID = K2CoreLib.K2Utils.GetDataField(Request.QueryString["sn"].ToString(), "OverTimeID");
                //string EmpID = K2CoreLib.K2Utils.GetDataField(Request.QueryString["sn"].ToString(), "EmpID");
                //string UserID = K2CoreLib.K2Utils.GetDataField(Request.QueryString["sn"].ToString(), "UserID");
                //string Approver = K2CoreLib.K2Utils.GetDataField(Request.QueryString["sn"].ToString(), "Approver");
                List<string> Datafield = new List<string>();

                // Mark person approve by Form
                Datafield.Add("Signer");
                Datafield.Add(SessionManager.UserDomain);

                //#region Xử lý gửi mail khi approver approve/reject
                //vHCS.SYS.Business.SYS_MailTemplateCollection col_mail = new vHCS.SYS.Business.SYS_MailTemplateCollection();
                //string MailApprove_Content = "";
                //string MailApprove_Subject = "";
                //string EmailApprove = "";
                //string EmailRequest="";
                
                ////Lấy nội dung mail approve
                //MailApprove_Content = col_mail.ReturnMailContent("TS_OverTime_Approve");
                //MailApprove_Content = MailApprove_Content.Replace("$Creator$", UserID);
                //MailApprove_Content = MailApprove_Content.Replace("$Status$", cboStatus.SelectedValue);
                //MailApprove_Content = MailApprove_Content.Replace("$Approver$", Approver);
                //MailApprove_Content = MailApprove_Content.Replace("$url$", ConfigurationManager.AppSettings.Get("History_OT") + OverTimeID + "&EmpID=" + EmpID);

                ////Lấy tiêu để mail approve
                //MailApprove_Subject = col_mail.ReturnSubjectMail("TS_OverTime_Approve");
                //MailApprove_Subject = MailApprove_Subject.Replace("$Status$",cboStatus.SelectedValue);
                //MailApprove_Subject = MailApprove_Subject.Replace("$Creator$", UserID);
                
                //EmailApprove = col_mail.ReturnEmail(Approver);
                //EmailRequest = col_mail.ReturnEmail(UserID);
                //#endregion

                ////Gán datafield
                //Datafield.Add("Mail_Requester");
                //Datafield.Add(EmailRequest);
                //Datafield.Add("Mail_Approver");
                //Datafield.Add(EmailApprove);
                //Datafield.Add("MailSubject_Approved");
                //Datafield.Add(MailApprove_Subject);
                //Datafield.Add("MailContent_Approved");
                //Datafield.Add(MailApprove_Content);
                ////End Gán datafield
                string sharedUser = Request.QueryString["SharedUser"] != null ? Request.QueryString["SharedUser"].ToString() : string.Empty;
                K2CoreLib.K2Utils.ActionExecute(Request.QueryString["sn"].ToString(), cboStatus.SelectedValue, sharedUser, Datafield.ToArray());
                btnSaveBot.Enabled = false;
                btnSaveTop.Enabled = false;

                //string[] ListOTID = OverTimeID.Split(',');

                //#region begin to save history
                //HR_WorkingRecordCollection cl_his = new HR_WorkingRecordCollection();
                //if (!cboStatus.SelectedValue.Equals("Reject"))
                //{
                //    cl_his.InsertHistory(Convert.ToInt64(ListOTID[0]), DateTime.Now, SessionManager.UserDomain, "Approver Step", "Approved", "", 3,0);
                //}
                //else
                //{
                //    cl_his.InsertHistory(Convert.ToInt64(ListOTID[0]), DateTime.Now, SessionManager.UserDomain, "Approver Step", "Rejected", "", 3,0);
                //}
                //#endregion End save
               
                //Insert History Comment 
                //TS_OverTimeCollection col = new TS_OverTimeCollection();
                //string eformid = col.SelectProcessID(Convert.ToInt64(ListOTID[0]));
                //K2CoreLib.K2Utils.InsertHistoryComment(eformid, SessionManager.UserDomain);
            }
            catch (Exception ex)
            {
                AlertMessage mess = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(mess);
            }
        }
        #endregion
    }
}